﻿using DotaHelp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;

namespace DotaHelp.Controllers
{
    public class GamesController : Controller
    {
        DotaModel model = new DotaModel();

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);  
            model.Dispose(); 
        }

        public ActionResult List()
        {
            return View();       
        }

        public ActionResult ItemTetris()
        {             
            return View(model.Items.Include("Recipes1").ToArray());
        }

        public ActionResult ItemTetrisResult(int id)
        {
            ViewBag.Items = model.Items.Include(i => i.Recipes).ToDictionary(i => i.Id);
            return View(model.Scores.First(s => s.Id == id));
        }

        [HttpPost]
        public void SaveScore(Score score)
        {
            Response.SaveUserName(score.Author); 
            score.Author = ControllerContext.HttpContext.PrepareUserName(score.Author);

            var maxoldscore = model.Scores.Where(s => s.Author == score.Author && s.GameName == score.GameName).Select(r=>r.Points).DefaultIfEmpty().Max();
            if (score.Points > maxoldscore)
            {
                score.Date = DateTime.UtcNow.NowByAstana();
                score.IpAddress = Request.ServerVariables["REMOTE_ADDR"];
                score.IsDeleted = false;

                model.Scores.AddObject(score);
                model.SaveChanges();
            }
        }

        
        public ActionResult ScoresForGame(string gameName)
        { 
            return PartialView(model.vSimpleScores.Where(g=>g.GameName == gameName).OrderByDescending(s => s.Points).Take(5).ToArray());
        }

        public ActionResult FullScoresForTetris(int? page)
        {
            return View(model.vSimpleScores.Where(g => g.GameName == "ItemTetris").ByPage(page, "raiting", s => s.Points, s => s.Date, ViewData, HttpContext).ToArray());
        }        
    }
}
